package com.upup.train_management.service.impl;

import com.upup.train_management.entity.Schedule;
import com.upup.train_management.entity.Ticket;
import com.upup.train_management.repository.ScheduleRepository;
import com.upup.train_management.repository.TicketRepository;
import com.upup.train_management.service.TicketService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Random;

@Service
public class TicketServiceImpl implements TicketService {

    private final TicketRepository ticketRepository;
    private final ScheduleRepository scheduleRepository;

    @Autowired
    public TicketServiceImpl(TicketRepository ticketRepository, ScheduleRepository scheduleRepository) {
        this.ticketRepository = ticketRepository;
        this.scheduleRepository = scheduleRepository;
    }

    @Override
    public List<Ticket> getAllTickets() {
        return ticketRepository.findAll();
    }

    @Override
    public Ticket getTicketById(Long id) {
        return ticketRepository.findById(id).orElse(null);
    }

    @Override
    public Ticket getTicketByNumber(String ticketNumber) {
        return ticketRepository.findByTicketNumber(ticketNumber);
    }

    @Override
    public List<Ticket> getTicketsByUserId(Long userId) {
        return ticketRepository.findByUserId(userId);
    }

    @Override
    public List<Ticket> getTicketsByScheduleId(Long scheduleId) {
        return ticketRepository.findByScheduleId(scheduleId);
    }

    @Override
    public List<Ticket> getTicketsByUserAndStatus(Long userId, String status) {
        return ticketRepository.findByUserIdAndStatus(userId, status);
    }

    @Override
    @Transactional
    public Ticket createTicket(Ticket ticket) {
        // 设置票号
        ticket.setTicketNumber(generateTicketNumber());

        // 设置创建时间
        ticket.setCreateTime(LocalDateTime.now());

        // 设置初始状态
        if (ticket.getStatus() == null) {
            ticket.setStatus("CONFIRMED");
        }

        return ticketRepository.save(ticket);
    }

    @Override
    @Transactional
    public Ticket updateTicket(Ticket ticket) {
        Ticket existingTicket = ticketRepository.findById(ticket.getId()).orElse(null);
        if (existingTicket == null) {
            return null;
        }

        // 保留原始创建时间和票号
        ticket.setCreateTime(existingTicket.getCreateTime());
        if (ticket.getTicketNumber() == null) {
            ticket.setTicketNumber(existingTicket.getTicketNumber());
        }

        return ticketRepository.save(ticket);
    }

    @Override
    @Transactional
    public boolean cancelTicket(Long ticketId) {
        Ticket ticket = ticketRepository.findById(ticketId).orElse(null);
        if (ticket == null) {
            return false;
        }

        // 检查是否可以取消票（例如，车次未发车）
        Schedule schedule = scheduleRepository.findById(ticket.getScheduleId()).orElse(null);
        if (schedule == null) {
            return false;
        }

        if (schedule.getDepartureDateTime().isBefore(LocalDateTime.now())) {
            return false; // 已发车，不能取消
        }

        ticket.setStatus("CANCELLED");
        ticketRepository.save(ticket);
        return true;
    }

    @Override
    public String generateTicketNumber() {
        LocalDateTime now = LocalDateTime.now();
        String datePart = now.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        String timePart = now.format(DateTimeFormatter.ofPattern("HHmmss"));
        String randomPart = String.format("%04d", new Random().nextInt(10000));

        return "TK" + datePart + timePart + randomPart;
    }
}